import { Component } from 'react';
import { ScrollList, Boxs, SearchBar, Badge, Toast, Tab, Button } from 'saltui';
const {HBox, Box, VBox} = Boxs;
const { IconButton } = Button;
import { URLS,nodataIcon } from '../../../app/variables';
import DB from '../../../app/db';
import './PageHome.less';

const F2 = require('@antv/f2/lib/core'); // 必须引入
require('@antv/f2/lib/geom/interval'); // 引入 interval 几何标记
require('@antv/f2/lib/coord/polar'); // 引入 极坐标
require('@antv/f2/lib/geom/adjust/stack'); // 引入数据层叠调整类型
// 第一步：加载插件 Legend
const Legend = require('@antv/f2/lib/plugin/legend');
// 第二步：注册插件 Legend
F2.Chart.plugins.register(Legend); // 这里进行全局注册，也可以给 chart 的实例注册
// 第一步：加载插件 Tooltip
const Tooltip = require('@antv/f2/lib/plugin/tooltip');
// 第二步：注册插件 Tooltip
F2.Chart.plugins.register(Tooltip); // 这里进行全局注册，也可以给 chart 的实例注册
const GroupAnimation = require('@antv/f2/lib/animation/group');
F2.Chart.plugins.register(GroupAnimation); // 这里进行全局注册，也可以给 chart 的实例注册

const currentItem = { activeItem: "0", flag: false};

const Item = React.createClass({
  detailsClick: function(event) {
    let t = this;
    let id = t.props.id;
    DB.SomeModuleAPI.taskIsExist({id:id}).then((content) => {
      if(content == 'notExist'){
        Toast.show({
            type: 'error',
            content: '当前数据已删除',
        });
        setTimeout(() => {
          t.onExit();  
        }, 2000);
      }else{
        currentItem.flag = true;
        location.hash = "meeting/taskView/"+id+"/"+t.props.applyRecordId+"/all";
      }
    }).catch((error) => {
    });
  },
  render:function() {
    let t = this;
    let type = t.props.type;
    var taskText = '';
    var endTime = t.props.endtime;
    if(endTime!=null && endTime!=undefined){
      endTime = endTime.split(" ")[0];
    }
    if(type === 'expiredData'){
      var now = new Date().getTime();
      var value = endTime.replace(/-/g, '/') + " 23:59:59";
      var end = new Date(value).getTime();
      var overDay = Math.ceil((now-end) / (24 * 3600 * 1000));
      taskText = "超期" + overDay + "天";
    }
    var progress = t.props.progress;
    var barHtml = '';
    if( progress <= 50 ) {
      var rotate = 'rotate('+(progress*3.6)+'deg)';
      barHtml = (
        <div className="circle-bar">
          <div className="circle-bar-left"></div>
          <div className="circle-bar-right" style={{"transform": rotate}}></div>
          <div className="mask">
            <span className="percent">{progress}</span>
          </div>
        </div>
      );
    }else {
      var rotate = 'rotate('+((progress-50)*3.6)+'deg)';
      barHtml = (
        <div className="circle-bar">
          <div className="circle-bar-left" style={{"transform": rotate}}></div>
          <div className="circle-bar-right" style={{'background-color': '#38adff','transform': 'rotate(0deg)'}}></div>
          <div className="mask">
            <span className="percent">{progress}</span>
          </div>
        </div>
      );
    }
    return <div>
      <HBox className="t-BCf t-ML16 t-MR16 t-MT10 t-P12 t-R4" onClick={t.detailsClick}>
        <Box flex={1}>
          <div className="t-omit t-FC3 t-FS16 t-LH1_3 t-MR8">
            {t.props.title}
          </div>
          <HBox vAlign="center">
            <Box className="" flex={1}>
              <HBox vAlign="center" className="t-FCddfontblue-60 t-LH1_3 t-PT6 t-FS14">
                <Box className="t-omit t-PR8">{t.props.resUserName}</Box>
                <Box>
                  <Badge className={type === 'expiredData'?'t-PL8':'t-DN'} text={taskText} style={{
                    lineHeight: '18px', height: '18px', padding: '0 8px', wordBreak: 'keep-all'
                  }} />
                </Box>
              </HBox>
              <Box className="t-FCddfontblue-40 t-LH1_3 t-PT6 t-FS12 t-omit">{'截止日期：' + endTime }</Box>
            </Box>
            <Box className="t-ML16">
              { barHtml }
            </Box>
          </HBox>
        </Box>
      </HBox>
    </div>
  }
});

export default class PageHome extends Component {
 constructor(props) {
    super(props);

    //修改待办列表页tab默认值
    document.getElementById("sendTabIndex").value = "0";
    //关闭加载页的遮罩效果
    $(".loading-containter").hide();
    //禁用ios弹性事件
    dd.ui.webViewBounce.disable();
   
    var winHeight = getScrollHigh(1, 1, 0);

    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    var winWidth = '';
    if(isAndroid==true){
      winWidth = window.screen.width-60+"px";
    }else if(isiOS==true){
      winWidth = window.screen.availWidth-60+"px";
    }else {
      if(window.screen.availWidth) {
        winWidth = '300px';
      }
    }

    var activeItem = '0';
    if(currentItem.flag){
      activeItem = currentItem.activeItem;
    }
    currentItem.flag = false;
    var applyRecordId = props.params.applyRecordId;
    this.state = {
      applyRecordId: applyRecordId,
      search0:'',
      search1:'',
      search2:'',
      noDataTip0:'暂无数据',
      noDataTip1:'暂无数据',
      noDataTip2:'暂无数据',
      expiredCount: 0,
      inProgressCount: 0,
      completeCount: 0,
      isCreatedOrEmcee: '1',
      allCount: 0,
      activeItem: activeItem,
      winHeight:winHeight,
      winWidth: winWidth,
      hasBottomTab: hasBottomTab
    };
  }

  componentDidMount(){
    var page_title = "会议任务";
    $("title").text(page_title);
    var thirdMenuType = getLoginUserInfo().thirdMenuType;
    if(thirdMenuType == 'DING'){
      dd.biz.navigation.setTitle({
          title : page_title,//控制标题文本，空字符串表示显示默认文本
          onSuccess : function(result) {},
          onFail : function(err) {}
      });
    }else if(thirdMenuType =='MH'){
      !!emp&&emp.window.setTitle({
          title: {
              text: page_title,
              icon: '',
              actionmenu: {}
          },
      });
    }
    this.countTaskInfos("");
    searchBarLimit(20);
  }

  countTaskInfos(title){
    let t = this;
    DB.SomeModuleAPI.taskInfosCount({applyrecordId: t.state.applyRecordId,title: title}).then((content) => {
      var completeCount = content.completeCount;
      var all = content.expiredCount+content.inProgressCount+completeCount;
      var taskRate = "";
      if(all != 0){
        taskRate = ((completeCount/all)*100).toFixed(0) + "%";
      }
      t.setState({
        expiredCount: content.expiredCount,
        inProgressCount: content.inProgressCount,
        completeCount: content.completeCount,
        isCreatedOrEmcee: content.isCreatedOrEmcee,
        taskRate: taskRate,
        allCount: all
      }); 
    }).catch((error) => {
    });
  }

  // 饼图
  crichart(map, cridata) {
    //var map = this.state.criMap;
    // Step 1: 创建 Chart 对象
    const chart = new F2.Chart({
      id: 'taskEcharts',
      pixelRatio: window.devicePixelRatio // 指定分辨率
    });

    // Step 2: 载入数据源
    chart.source(cridata);

    chart.tooltip({
      onShow: function onShow(ev) {
        var items = ev.items;
        var origin = items[0].origin;
        items[0].value = origin.count + "个";
      }
    });

    chart.legend({
      position: 'top',
      itemFormatter: function itemFormatter(val) {
        return val + '  ' + (map[val]*100).toFixed(0)+"%";
      }
    });
    // Step 3：创建图形语法，绘制柱状图，由 genre 和 sold 两个属性决定图形位置，genre 映射至 x 轴，sold 映射至 y 轴
    chart.coord('polar', {
      transposed: true,
      radius: 0.85
    });
    chart.axis(false);
    chart.interval().position('a*percent').color('name', ['#FFDB5B', '#31C5E9', '#37A2DA']).adjust('stack').style({
      lineWidth: 1,
      stroke: '#fff',
      lineJoin: 'round',
      lineCap: 'round'
    });

    // Step 4: 渲染图表
    chart.render();
  }

  // 请求参数
  beforeFetch0(data,from){
    if (from.title == undefined) {
      data.title = this.state.search0;
    } else {
      data.title = from.title;
    }
    data.status = '0';
    data.applyRecordId = this.state.applyRecordId;
    return data;
  }

  beforeFetch1(data,from){
    if (from.title == undefined) {
      data.title = this.state.search1;
    } else {
      data.title = from.title;
    }
    data.status = '1';
    data.applyRecordId = this.state.applyRecordId;
    return data;
  }

  beforeFetch2(data,from){
    if (from.title == undefined) {
      data.title = this.state.search2;
    } else {
      data.title = from.title;
    }
    data.status = '2';
    data.applyRecordId = this.state.applyRecordId;
    return data;
  }

  fetchData0(param){
    this.refs.task_expiredData_ref.fetchData({title:''});
  }

  fetchData1(param){
    this.refs.task_inProgressData_ref.fetchData({title:''});
  }

  fetchData2(param){
    this.refs.task_completeData_ref.fetchData({title:''});
  }

   //搜索
   onSearch(type,keyword) {
      if (type == 0) {
        this.setState({
          search0:keyword,
          noDataTip0:'无搜索结果'
        });
        this.refs.task_expiredData_ref.fetchData({title:keyword});
      } else if (type == 1) {
        this.setState({
          search1:keyword,
          noDataTip1:'无搜索结果'
        });
        this.refs.task_inProgressData_ref.fetchData({title:keyword});
      } else if (type == 2) {
        this.setState({
          search2:keyword,
          noDataTip2:'无搜索结果'
        });
        this.refs.task_completeData_ref.fetchData({title:keyword});
      }
      this.countTaskInfos(keyword);
   }

  //退出
  onExit(type){
    this.countTaskInfos("");
    if (type == 0) {
      this.setState({
        search0:'',
        noDataTip0:'暂无数据'
      });
      this.refs.task_expiredData_ref.fetchData({title:''});
    } else if (type == 1) {
      this.setState({
        search1:'',
        noDataTip1:'暂无数据'
      });
      this.refs.task_inProgressData_ref.fetchData({title:''});
    } else if (type == 2) {
      this.setState({
        search2:'',
        noDataTip2:'暂无数据'
      });
      this.refs.task_completeData_ref.fetchData({title:''});
    }
  }

  handleChange(obj) {
    this.setState({
      activeItem: obj.active,
      search0:'',
      search1:'',
      search2:'',
    });
    currentItem.activeItem = obj.active;
    searchBarLimit(20);

    var allCount = this.state.allCount;
    if(obj.active=='3' && allCount!=0){
      var expiredCount=this.state.expiredCount, inProgressCount=this.state.inProgressCount, completeCount=this.state.completeCount;
      var expired = 0, inProgress = 0, complete = 0;
      complete = (completeCount/allCount).toFixed(2);
      if(expiredCount == inProgressCount){
        expired = ((1-complete)/2).toFixed(2);
        inProgress = expired;
      }else if(expiredCount == completeCount){
        expired = complete;
        inProgress = (1 - expired*2).toFixed(2);
      }else if(inProgressCount == completeCount){
        inProgress = complete;
        expired = (1 - complete*2).toFixed(2);
      }else{
        inProgress = (inProgressCount/allCount).toFixed(2);
        expired = (1 - complete - inProgress).toFixed(2);
      }

      var cridata = [
        { name: '超期', percent: expired*1, a: '1', count: this.state.expiredCount },
        { name: '进行中', percent: inProgress*1, a: '1', count: this.state.inProgressCount },
        { name: '已完成', percent: complete*1, a: '1', count: this.state.completeCount }
      ];
      var criMap = { '超期': expired, '进行中': inProgress, '已完成': complete };

      this.crichart(criMap, cridata);
    }
  }

  addTaskInfo(){
    location.hash = "meeting/taskAdd/"+this.state.applyRecordId;
  }

  render() {
    const t = this;
    let listHeight = {height: this.state.winHeight};
    return (
      <div>
        <Tab activeKey={this.state.activeItem} onChange={this.handleChange.bind(this)}>
          <Tab.Item title={"已超期(" + t.state.expiredCount + ")"} key="0">
            <SearchBar hasHistory={false} instantSearch={false} onSearch={this.onSearch.bind(this,0)}  ref='expiredData_search' placeholder='请输入任务名称' onExit={this.onExit.bind(this,0)}>
            </SearchBar>
            <div className="dd-task" style={listHeight}>
              <ScrollList
                url={URLS.findTaskList}
                dataType="json"
                pageSize={10}
                beforeFetch={this.beforeFetch0.bind(this)}
                noDataTip={this.state.noDataTip0}
                processData={(data) => data}
                ref = 'task_expiredData_ref'
                noDataImage={nodataIcon}
                scrollLoad={true}
                currentPageKey="page">
                <Item type="expiredData" refreshList={this.fetchData0.bind(this)}/>
              </ScrollList>
            </div>
          </Tab.Item>
          <Tab.Item title={"进行中(" + t.state.inProgressCount + ")"} key="1">
            <SearchBar hasHistory={false} instantSearch={false} onSearch={this.onSearch.bind(this,1)}  ref='inProgressData_search' placeholder='请输入任务名称' onExit={this.onExit.bind(this,1)}>
            </SearchBar>
            <div className="dd-task" style={listHeight}>
              <ScrollList
                url={URLS.findTaskList}
                dataType="json"
                pageSize={10}
                beforeFetch={this.beforeFetch1.bind(this)}
                noDataTip={this.state.noDataTip1}
                processData={(data) => data}
                ref = 'task_inProgressData_ref'
                noDataImage={nodataIcon}
                currentPageKey="page">
                <Item type="inProgressData" refreshList={this.fetchData1.bind(this)} />
              </ScrollList>
            </div>
          </Tab.Item>
          <Tab.Item title={"已完成(" + t.state.completeCount + ")"} key="2">
            <SearchBar hasHistory={false} instantSearch={false} onSearch={this.onSearch.bind(this,2)}  ref='completeData_search' placeholder='请输入任务名称' onExit={this.onExit.bind(this,2)}>
            </SearchBar>
            <div className="dd-task" style={listHeight}>
              <ScrollList
                url={URLS.findTaskList}
                dataType="json"
                pageSize={10}
                beforeFetch={this.beforeFetch2.bind(this)}
                noDataTip={this.state.noDataTip2}
                processData={(data) => data}
                ref = 'task_completeData_ref'
                noDataImage={nodataIcon}
                scrollLoad={true}
                currentPageKey="page">
                <Item type="completeData" refreshList={this.fetchData2.bind(this)}/>
              </ScrollList>
            </div>
          </Tab.Item >
          <Tab.Item title="统计" key="3">
            <h1 className='t-FAC t-FS16 t-LH44'><b>任务完成情况统计</b></h1>
            <HBox className='t-FBJ t-PL16 t-PR16 t-LH40 t-BCf'>
              <Box>任务完成率</Box>
              <Box>{this.state.taskRate}</Box>
            </HBox>
            { this.state.taskRate=="" || this.state.taskRate==null || this.state.taskRate==undefined ? 
              <div id="nodataHeight" style={{position: 'relative',height:"350"}}>
                <div className="nodata-wrapper">
                  <VBox vAlign="center" hAlign="center" className="nodata">
                      <Box>
                        <div>
                           <img src={nodataIcon} alt="" style={{width: 68 + 'px'}} />
                         </div>
                      </Box>
                      <Box className="t-FC6">
                          暂无数据
                      </Box>
                  </VBox>
                </div>
              </div> 
              :
              <div style={{"text-align":"center"}}>
                <canvas id="taskEcharts" style={{width:this.state.winWidth,height:this.state.winWidth}}></canvas>
              </div>
            }
          </Tab.Item>
        </Tab>
        <IconButton className={this.state.isCreatedOrEmcee=='0'?'add-new-page t-BCddblue':'t-DN'} onClick={this.addTaskInfo.bind(this)}><i className="iconfont icon-plus t-FCf"></i></IconButton>
      </div>
    );
  }
}